import { defineStore } from 'pinia'
import { 
  fetchAllNews, 
  fetchSingleNews, 
  addNews, 
  fetchComments, 
  addComment 
} from '@/services/api'

export const useNewsStore = defineStore('news', {
  state: () => ({
    newsList: [],
    currentNews: null,
    comments: [],
    loading: false,
    commentsLoading: false
  }),
  actions: {
    async fetchNews() {
      this.loading = true
      try {
        const response = await fetchAllNews()
        this.newsList = response.data
        return this.newsList
      } catch (error) {
        console.error('获取新闻列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchSingleNews(id) {
      this.loading = true
      try {
        const response = await fetchSingleNews(id)
        this.currentNews = response.data
        return this.currentNews
      } catch (error) {
        console.error('获取新闻详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async addNews(newsData) {
      try {
        const response = await addNews({
          ...newsData,
          createdAt: new Date().toISOString(),
          author: '当前用户名' // 实际应从store获取
        })
        this.newsList.unshift(response.data)
        return response.data
      } catch (error) {
        console.error('添加新闻失败:', error)
        throw error
      }
    },
    
    async fetchComments(newsId) {
      this.commentsLoading = true
      try {
        const response = await fetchComments(newsId)
        this.comments = response
        return this.comments
      } catch (error) {
        console.error('获取评论失败:', error)
        throw error
      } finally {
        this.commentsLoading = false
      }
    },
    
    async addComment(commentData) {
      try {
        const response = await addComment({
          ...commentData,
          createdAt: new Date().toISOString()
        })
        this.comments.push(response.data)
        return response.data
      } catch (error) {
        console.error('添加评论失败:', error)
        throw error
      }
    }
  }
})